#!/usr/bin/env python3
# 项目启动脚本

import subprocess
import sys
import time
import requests
from pathlib import Path

def run_command(cmd, cwd=None):
    """执行命令"""
    print(f"执行: {cmd}")
    result = subprocess.run(cmd, shell=True, cwd=cwd)
    return result.returncode == 0

def check_service(url, name, timeout=30):
    """检查服务状态"""
    print(f"检查 {name} 服务...")
    for i in range(timeout):
        try:
            response = requests.get(url, timeout=5)
            if response.status_code == 200:
                print(f"✅ {name} 服务正常")
                return True
        except:
            pass
        time.sleep(1)
    print(f"❌ {name} 服务启动失败")
    return False

def main():
    """主函数"""
    project_root = Path(__file__).parent.parent
    
    print("🚀 启动音视频转换微服务...")
    
    # 构建并启动服务
    if not run_command("docker-compose up -d --build", cwd=project_root):
        print("❌ 服务启动失败")
        sys.exit(1)
    
    print("⏳ 等待服务启动...")
    time.sleep(10)
    
    # 检查服务状态
    services = [
        ("http://localhost:8000", "音频转文字"),
        ("http://localhost:8001", "视频转语音"),
        ("http://localhost:8002/health", "API网关")
    ]
    
    all_ok = True
    for url, name in services:
        if not check_service(url, name):
            all_ok = False
    
    if all_ok:
        print("\n🎉 所有服务启动成功!")
        print("📚 API文档: http://localhost:8002/docs")
        print("🔍 健康检查: http://localhost:8002/health")
    else:
        print("\n❌ 部分服务启动失败，请检查日志")
        run_command("docker-compose logs", cwd=project_root)
        sys.exit(1)

if __name__ == "__main__":
    main()